package offerbook;

import java.util.Stack;

/**
 * O(1)时间获取栈min。 额外空间 < O(n)
 */
public class Code21_GetStackMin2 {
    private Stack<Integer> dataStack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();

    public void push(int node) {
        dataStack.push(node);
        if(minStack.isEmpty()){
            minStack.push(node);
            return;
        }
        //只有node比栈顶的更小或者等于，才入栈
        if(node <= minStack.peek()){
            minStack.push(node);
        }
    }
    
    public void pop() {
        if(dataStack.isEmpty()) return;
        Integer pop = dataStack.pop();
        //栈顶和min栈顶一样，min就出站
        if(pop == minStack.peek())
            minStack.pop();
    }
    
    public int top() {
        if(dataStack.isEmpty()) throw new RuntimeException("empty");
        return dataStack.peek();
    }
    
    public int min() {
        if(minStack.isEmpty()) throw new RuntimeException("empty");
        return minStack.peek();
    }
}